package com.multisource.myself.config;


import com.multisource.myself.common.DataSourceType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandler;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;


import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Terry.L
 */
@Configuration
//@MapperScan(basePackages = "com.multisource.myself.mapper")
public class MybatisConfig {

    @Bean("dynamicDataSource")
    public DynamicDataSource dataSource(@Qualifier("dataSource") DataSource mysqlDataSource,
                                        @Qualifier("prestoDataSource") DataSource prestoDataSource) {
        Map<Object, Object> map = new HashMap<>(2);
        map.put(DataSourceType.MYSQL, mysqlDataSource);
        map.put(DataSourceType.PRESTO, prestoDataSource);
 //sd
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(map);
        dynamicDataSource.setDefaultTargetDataSource(mysqlDataSource);

        return dynamicDataSource;
    }


    @Bean
    @DependsOn({"dynamicDataSource"})
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource dynamicDataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

        Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml");
        org.apache.ibatis.session.Configuration myBatisConfiguration = new org.apache.ibatis.session.Configuration();
        myBatisConfiguration.setMapUnderscoreToCamelCase(true);
        myBatisConfiguration.setCallSettersOnNulls(true);
        myBatisConfiguration.setCacheEnabled(false);

        //引入DataSource
        factoryBean.setDataSource(dynamicDataSource);
        //读取mapper.xml
        factoryBean.setMapperLocations(resources);
        //增加处理value中的空格
        factoryBean.setTypeHandlers(new TypeHandler[]{new MyStringTypeHandler()});
        //开启别名自动解析
        factoryBean.setConfiguration(myBatisConfiguration);
        //查出列名自动转驼峰
//        factoryBean.setObjectWrapperFactory(new MapWrapperFactory());

        return factoryBean.getObject();
    }

    @Bean
    @DependsOn({"dynamicDataSource"})
    public PlatformTransactionManager transactionManager(DynamicDataSource dynamicDataSource) {
        return new DataSourceTransactionManager(dynamicDataSource);
    }

}
